layui.use(['table', 'admin', 'ax', 'form'], function () {
    var $ = layui.$;
    var table = layui.table;
    var $ax = layui.ax;
    var admin = layui.admin;
    var form = layui.form;

    /**
     * 收货单位表管理
     */
    var BasicPutgoods = {
        tableId: "basicPutgoodsTable"
    };

    /**
     * 往来地址表管理
     */
    var BasicAddress = {
        tableId: "basicAddressTable"
    };

    /**
     * 初始化表格的列
     */
    BasicPutgoods.initColumn = function () {
        return [[
            {type: 'checkbox'},
            {field: 'id', hide: true, title: 'Primary Key'},
            {align: 'center',width: 120, toolbar: '#tableBar', title: 'Operations'},
            {field: 'putgoodsOperateName', title: 'Customer Name'},
            {field: 'putgoodsName', title: 'Unit Name', style:'font-weight: 600;'},
            {field: 'unitNumber', title: 'Unit Number', style:'font-weight: 600;'},
            {field: 'putgoodsNotes', title: 'Delivery Notes'},
            {field: 'unitCategory', title: 'Unit Category'},
            {field: 'unitType', title: 'Unit Type'},
            {field: 'createTime', title: 'Creation Time'},
        ]];
    };

    /**
     * 点击查询按钮
     */
    BasicPutgoods.search = function () {
        var queryData = {};
        queryData['condition'] = $("#condition").val();
        queryData['unitNumber'] = $("#unitNumber").val();
        queryData['putgoodsCustomerId'] = $("#putgoodsCustomerId").val();
        queryData['unitCategory'] = $("#unitCategory").val();
        queryData['unitType'] = $("#unitType").val();
        table.reload(BasicPutgoods.tableId, {
            where: queryData, page: {curr: 1},
             done:function () {
            }
        });
    };
    
    // 导入
    $('#btnExpimport').click(function () {
        layer.open({
            type: 2,
            title: 'Unit Address Import',
            area: ['1000px', '750px'],
            anim: 5,
            content: Feng.ctxPath + '/basicPutgoods/toimportExcel',
            end: function () {
                table.reload(BasicPutgoods.tableId);
            }
        });
    });
    
    // 导入
    $('#btnExpimportUpdate').click(function () {
        layer.open({
            type: 2,
            title: 'Update Unit Address Import',
            area: ['1000px', '750px'],
            anim: 5,
            content: Feng.ctxPath + '/basicPutgoods/toimportExcelupdate',
            end: function () {
                table.reload(BasicPutgoods.tableId);
            }
        });
    });

    // 添加按钮点击事件
    $('#btnAdd').click(function () {
        layer.open({
            type: 2,
            title: 'Add Customer',
            area: ['900px', '750px'],
            anim: 5,
            content: Feng.ctxPath + '/basicPutgoods/add',
            end: function () {
                table.reload(BasicPutgoods.tableId);
            }
        });
    });

    /**
     * 导出excel按钮
     */
    BasicPutgoods.exportExcel = function () {
        var checkRows = table.checkStatus(BasicPutgoods.tableId);
        if (checkRows.data.length > 0) {
            table.exportFile(tableResult.config.id, checkRows.data, 'xls');
        } else {
			window.location.href = Feng.ctxPath + '/basicPutgoods/exportExcelBySpec?putgoodsCustomerId='+$("#putgoodsCustomerId").val()
			+"&condition="+$("#condition").val()+"&unitCategory="+$("#unitCategory").val()
			+"&unitNumber="+$("#unitNumber").val()+"&unitType="+$("#unitType").val();
        }
    };

    /**
     * 点击删除
     *
     * @param data 点击按钮时候的行数据
     */
    BasicPutgoods.onDeleteItem = function (data) {
        var operation = function () {
            var ajax = new $ax(Feng.ctxPath + "/basicPutgoods/delete", function (data) {
				if(data.success){
	                Feng.success("Deletion successful!");
	                table.reload(BasicPutgoods.tableId);
				} else {
                	Feng.error("Deletion failed!" + data.message + "!");
				}
            }, function (data) {
                Feng.error("Deletion failed!" + data.responseJSON.message + "!");
            });
            ajax.set("id", data.id);
            ajax.start();
        };
        Feng.confirm("Are you sure to delete?", operation);
    };

    // 渲染表格
    var tableResult = table.render({
        elem: '#' + BasicPutgoods.tableId,
        url: Feng.ctxPath + '/basicPutgoods/list',
        page: true,
        limit: 60,
		limits:[60,120,240,360,480,600],
        toolbar: '#toolbarDemo', //开启头部工具栏，并为其绑定左侧模板
        height: 400,
        cellMinWidth: 100,
        cols: BasicPutgoods.initColumn()
    });

    // 搜索按钮点击事件
    $('#btnSearch').click(function () {
        BasicPutgoods.search();
    });

    // 导出excel
    $('#btnExp').click(function () {
        BasicPutgoods.exportExcel();
    });

    // 工具条点击事件
    table.on('tool(' + BasicPutgoods.tableId + ')', function (obj) {
        var data = obj.data;
        var layEvent = obj.event;

        if (layEvent === 'edit') {
	        layer.open({
	            type: 2,
	            title: 'Edit Customer',
	            area: ['900px', '750px'],
	            anim: 5,
	            content: Feng.ctxPath + '/basicPutgoods/edit?id=' + data.id,
	            end: function () {
	                table.reload(BasicPutgoods.tableId);
	            }
	        });
        } else if (layEvent === 'delete') {
            BasicPutgoods.onDeleteItem(data);
        }
    });

    /**
     * 初始化 详细地址  表格的列
     */
    BasicAddress.initColumn = function () {
        return [[
            {type: 'checkbox'},
            {field: 'id', hide: true, title: 'Primary Key'},
            {align: 'center', width: 120 , toolbar: '#tableBarAddress', title: 'Operations'},
            {field: 'address', title: 'Detailed Address', style:'color: #19be6b;font-weight: 600;',width:350},
            {field: 'contacts', title: 'Contact Person', style:'font-weight: 600;'},
            {field: 'tel', title: 'Contact Phone', style:'font-weight: 600;'},
            {field: 'lineName', title: 'Affiliated Route', style:'font-weight: 600;'},
            {field: 'switchWl', title: 'Geofence Switch', templet: '#switchWlTpl'},
            {field: 'switchBj', title: 'Pickup Geofence Radius', style:'font-weight: 600;'},
            {field: 'switchBj2', title: 'Delivery Geofence Radius', style:'font-weight: 600;'},
            {field: 'longitude', title: 'Longitude', style:'font-weight: 600;'},
            {field: 'latitude', title: 'Latitude', style:'font-weight: 600;'},
            {field: 'kilometer', title: 'Distance (km)', style:'font-weight: 600;'},
            {field: 'sheng', title: 'Province', style:'font-weight: 600;'},
            {field: 'shi', title: 'City', style:'font-weight: 600;'},
            {field: 'qu', title: 'District', style:'font-weight: 600;'},
            {field: 'jie', title: 'Street', style:'font-weight: 600;'}
        ]];
    };

    // 单击行事件
    table.on('row(' + BasicPutgoods.tableId + ')', function (obj) {
        var data = obj.data;
		$('div[lay-id="' + BasicPutgoods.tableId + '"]').find(".layui-table-body tr ").attr({ "style": "background:#FFFFFF" });//其他tr恢复原样
		$('div[lay-id="' + BasicPutgoods.tableId + '"]').find(obj.tr.selector).attr({ "style": "background:#e6e6e6" });//改变当前tr颜色
        address(data);
    });

    $('#weChat').click(function () {
        layer.open({
            type: 2,
            title: 'Recipient Unit WeChat Registration Code',
            area: ['1000px', '550px'],
            anim: 5,
            content: Feng.ctxPath + '/basicPutgoods/toqrCode',
            end: function () {
            }
        });
    });

    $('#zongjuli').click(function () {
    	var msg;
        $.ajax({
        	url:Feng.ctxPath + "/basicPutgoods/zongzhixian",
			data:{putgoodsCustomerId:$("#putgoodsCustomerId").val()},
        	cache: false,
        	dataType:"json",
        	beforeSend:function(){
        		msg = layer.msg('Calculating... Please wait patiently', {
        			  icon: 16,
        			  shade: [0.2,'#000'], //0.1透明度的白色背景
        			  time: false
        		});
        	},
        	success:function(data){
            	layer.close(msg); 
        		if (data.success) {
    				var msg2 =  layer.open({
    					  title: 'Notification' ,
    					  content: data.data,
    					  btn: ['Confirm'],
    					  yes: function (){
    						  layer.close(msg2);
    					  }
    				});  
				} else {
                    Feng.error("Operation failed! "+data.message);
				}
        	},
        	error:function(data){
            	layer.close(msg); 
                Feng.error("Operation failed! " + data.responseJSON.message)
        	}
        })

        return false;
    });
    
    function address(data){
    	var putgoodsId;
    	var condition = '';
    	if (data!=null) {
    		$("#putgoodsId").val(data.id);
    		putgoodsId = data.id;
		} else {
			putgoodsId = 0;
			condition = 'ndate';
		}
        // 渲染表格
        var tableResult = table.render({
            elem: '#' + BasicAddress.tableId,
            url: Feng.ctxPath + '/basicAddress/list?putgoodsId='+putgoodsId+"&condition="+condition,
            page: true,
            limit: 20,
            height: 370,
            toolbar: '#toolbarfromAddress',
            cellMinWidth: 100,
            cols: BasicAddress.initColumn()
        });

        // 添加按钮点击事件
        $('#btnAddAddress').click(function () {
            layer.open({
                type: 2,
                title: 'Address Entry',
                area: ['900px', '750px'],
                anim: 5,
                content: Feng.ctxPath + '/basicAddress/add?putgoodsId='+putgoodsId,
                end: function () {
                	address(data);
                }
            });
        });

        /**
         * 点击编辑
         *
         * @param data 点击按钮时候的行数据
         */
        BasicAddress.openEditDlg = function (data2) {
            layer.open({
                type: 2,
                title: 'Edit Address',
                area: ['1000px', '800px'],
                anim: 5,
                content: Feng.ctxPath + '/basicAddress/edit?id='+data2.id,
                end: function () {
                	address(data);
                }
            });
        };

        /**
         * 点击删除
         *
         * @param data 点击按钮时候的行数据
         */
        BasicAddress.onDeleteItem = function (data2) {
            var operation = function () {
                var ajax = new $ax(Feng.ctxPath + "/basicAddress/delete", function (data2) {
					if(data2.success){
	                    Feng.success("Deletion successful!");
	                	address(data);
					} else {
	                	Feng.error("Deletion failed!" + data2.message + "!");
					}
                }, function (data2) {
                    Feng.error("Deletion failed!" + data2.responseJSON.message + "!");
                });
                ajax.set("id", data2.id);
                ajax.start();
            };
            Feng.confirm("Are you sure to delete?", operation);
        };
        
        // 工具条点击事件
        table.on('tool(' + BasicAddress.tableId + ')', function (obj) {
            var data = obj.data;
            var layEvent = obj.event;
            if (layEvent === 'editAddress') {
                BasicAddress.openEditDlg(data);
            } else if (layEvent === 'deleteAddress') {
                BasicAddress.onDeleteItem(data);
            }
        });

	    // 修改参数状态
	    form.on('switch(switchWl)', function (obj) {
	        var id = obj.elem.value;
	        var checked = obj.elem.checked ? true : false;
	
	        BasicAddress.changeGradingStatus(id, checked);
	    });
	
	    /**
	     * 修改参数状态
	     *
	     * @param id 参数id
	     * @param checked 是否选中（true,false），选中就是启用用户，未选中就是禁用用户
	     */
	    BasicAddress.changeGradingStatus = function (id, checked) {
	        if (checked) {
	            var ajax = new $ax(Feng.ctxPath + "/basicAddress/editItemswitchWl", function (data2) {
	                Feng.success("Enabled successfully!");
	            }, function (data) {
	                Feng.error("Failed to enable!");
                	address(data);
	            });
	            ajax.set("switchWl", 1);
	            ajax.set("id", id);
	            ajax.start();
	        } else {
	            var ajax = new $ax(Feng.ctxPath + "/basicAddress/editItemswitchWl", function (data2) {
	                Feng.success("Disabled successfully!");
	            }, function (data) {
	                Feng.error("Failed to disable!" + data.responseJSON.message + "!");
                	address(data);
	            });
	            ajax.set("switchWl", 2);
	            ajax.set("id", id);
	            ajax.start();
	        }
	    };
    }
    
});
